<!--
*@Author: QWP
*@Description: 人员其他基本信息的编辑
*@Date: 2024-07-08 17:04:38
-->
<template>
  <a-drawer
    :title="drawerTitle"
    placement="right"
    width="60%"
    :bodyStyle="bodyStyle"
    rootClassName="u-person-detial-drawer"
    v-bind="$attrs"
    @close="dialogClose">
    <u-card v-for="(item, index) in form"
      :title="drawerTitle + numberToText(index + 1)"
      class="f-margin-b16">
      <template #extra>
        <u-icon-font type="icon-a-shanchu1" 
          style="color: #1890ff"
          @click="form.splice(index, 1)">
        </u-icon-font>
      </template>
      <u-form :elements="formEls"
        :model="form[index]"
        :gutter="16"
        :loading="formLoading"
        :rule="getRules(index)"
        v-if="refresh"
        @formChange="(value) => formChange(value, index)"
        ref="formRef">
      </u-form>
    </u-card>
    <u-icon-button itype="add" @click="addBtn" :loading="formLoading">添加</u-icon-button>

    <template #footer>
      <a-row justify="end" class="f-padding-tb8">
        <a-space>
          <u-icon-button itype="save" @click="submit" :loading="formLoading">保存</u-icon-button>
          <u-icon-button itype="delete" @click="deleteAll" :loading="formLoading">清除全部</u-icon-button>
          <u-icon-button itype="close" @click="dialogClose">关闭</u-icon-button>
        </a-space>
      </a-row>
    </template>
  </a-drawer>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted, h, useAttrs, watch, nextTick } from 'vue' 
import { useLoginStore,  useBaseStore } from '@/store'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { _IFormEl, _IExtra } from '@/components/common/form/interface';
import { FormInstance, FormItemProps } from 'ant-design-vue';
import { HomeOutlined, FileTextOutlined, UploadOutlined } from '@ant-design/icons-vue';
import { TreeProps } from 'ant-design-vue/es/vc-tree';
import { ColumnProps } from 'ant-design-vue/es/table';
import { _IColumnProps } from '@/components/common/tableEdit/interface.ts'
import { fileCols } from '@/common/model/fileCols'
import { cloneDeep } from 'lodash'
import { numberToText } from '@/common/model/base'
import { alertC, messageC, numberC, isValue } from '@/util/common'
import { collapses } from './data/data.ts'
import { getCurrentApi } from '@/views/oa/personnelManager/personInfo/data/api.ts'
import dayjs from 'dayjs';

const props = withDefaults(defineProps<{
  params: object | any,
  keyid?: string,
  baseInfo: object | any
}>(), {
  params: {},
  baseInfo: {}
})
const route = useRoute()
const attrs = useAttrs()
const { userInfo } = storeToRefs(useLoginStore())

const emits = defineEmits(['success', 'close'])

// 表单相关信息
const refresh = ref<boolean>(true)
const formRef = ref<FormInstance>()
const form = ref<any[]>([])
const formLoading = ref<boolean>(false)

const bodyStyle = {
  background: 'rgb(245, 246, 247)'
}

// 所有元素类型
const formEls = computed(() => {
  return props.params['editForm'] || []
})

const drawerTitle = computed(() => props.params['label'])

// 添加更多
const addBtn = () => {
  form.value.push(initBaseInfo())
}

// 确认提交
const submit = async () => {
  for(let i = 0; i < form.value.length; i++) {
    await formRef.value[i].form.validate()
  }

  const api = getCurrentApi(props.params.activeKey);
  if(!api) {
    return
  }

  formLoading.value = true;
  try {
    const res = await api.add(form.value)
    if(res.code == 0) {
      emits('success', props.params.activeKey);
      messageC(res.msg, 'success')
    }
    else {
      messageC(res.msg, 'warning')
    }
  } catch (error) {}
  formLoading.value = false;

}

// 初始化默认保存传递的数据
const initBaseInfo = () => {
  return {
    perInfoNoId: props.baseInfo['keyid'] || '',
  }
}

// 设置规则
const getRules = (index) => {
  const { activeKey } = props.params || {}
  const formItem = form.value[index]
  // 专家
  if(activeKey == 'expert') {
    return {
      beginDate: [
        {  trigger: 'change', validator: async(_rule: Rule, value: string) => {
            if(value && formItem['endDate']) {
              if(dayjs(formItem['endDate']).isBefore(dayjs(value))) {
                return Promise.reject('聘用开始时间不能晚于聘用结束时间');
              }
              return Promise.resolve()
            }
          } 
        }
      ],
      endDate: [
        {  trigger: 'change', validator: async(_rule: Rule, value: string) => {
            if(value && formItem['beginDate']) {
              if(dayjs(formItem['beginDate']).isAfter(dayjs(value))) {
                return Promise.reject('聘用结束时间不能早于聘用开始时间');
              }
              return Promise.resolve()
            }
          } 
        }
      ],
    }
  }
  // 合同
  else if(activeKey == 'contract') {
    return {
      beginDate: [
        {  trigger: 'change', validator: async(_rule: Rule, value: string) => {
            if(value && formItem['endDate']) {
              if(dayjs(formItem['endDate']).isBefore(dayjs(value))) {
                return Promise.reject('开始时间不能晚于结束时间');
              }
              return Promise.resolve()
            }
          } 
        }
      ],
      endDate: [
        {  trigger: 'change', validator: async(_rule: Rule, value: string) => {
            if(value && formItem['beginDate']) {
              if(dayjs(formItem['beginDate']).isAfter(dayjs(value))) {
                return Promise.reject('结束时间不能早于开始时间');
              }
              return Promise.resolve()
            }
          } 
        }
      ],
    }
  }
  // 外派
  else if(activeKey == 'outsend') {
    return {
      beginDate: [
        {  trigger: 'change', validator: async(_rule: Rule, value: string) => {
            if(value && formItem['endDate']) {
              if(dayjs(formItem['endDate']).isBefore(dayjs(value))) {
                return Promise.reject('开始时间不能晚于结束时间');
              }
              return Promise.resolve()
            }
          } 
        }
      ],
      endDate: [
        {  trigger: 'change', validator: async(_rule: Rule, value: string) => {
            if(value && formItem['beginDate']) {
              if(dayjs(formItem['beginDate']).isAfter(dayjs(value))) {
                return Promise.reject('结束时间不能早于开始时间');
              }
              return Promise.resolve()
            }
          } 
        }
      ],
    }
  }
}

const formChange = ({ key, value }, index) => {
  const { activeKey } = props.params || {}
  // 学历
  if(activeKey == 'education') {
    if(key == 'certificate') {
      let vals = value ? value.split(',') : []
      form.value[index]['degreeCertificate'] = vals.length == 0 ? '' : `${vals.length - 1}`
    }
    // 最高学历
    else if('isHighestDegree' == key) {
      if(value == 1) {
        form.value.forEach((item, index1) => {
          if(index1 != index) {
            item[key] = 0
          }
        })
      }
    }
  }
  // 外派
  else if(activeKey == 'outsend') {
    if(['beginDate', 'endDate'].includes(key)) {
      if(form.value[index]['beginDate'] && form.value[index]['endDate']) {
        form.value[index]['number'] = dayjs(form.value[index]['endDate']).diff(dayjs(form.value[index]['beginDate']), 'day') + 1
      } 
      else {
        form.value[index]['number'] = 0
      }
    }
  }
}

// 获取已存在的数据
const echoInfo = async () => {
  // 是否已经初始添加了一条数据
  let isInitFirst = false;
  
  const api = getCurrentApi(props.params.activeKey);
  if(!api || !props.baseInfo['keyid']) {
    addBtn()
    return
  }

  formLoading.value = true
  try {
    const res = await api.page({
      model: { 
        keywords: null, 
        perInfoNoId: props.baseInfo['keyid'] || ''
      },
      current: 1,
      size: 2000,
    })
    if(res.code == 0) {
      let records = res.data.records || [];
      if(records.length == 0) {
        addBtn()
      }
      else {
        records.forEach(item => {
          item.appendixSaveVOList = item.attachList || []
        })
        form.value = records
      }
    }
  } catch (error) {}
  refresh.value = false;
  nextTick(() => {
    refresh.value = true;
  })
  formLoading.value = false
}

// 清除全部
const deleteAll = () => {
  form.value = []
}

// 弹窗关闭
const dialogClose = () => {
  form.value = []
  emits('close')
}

watch(() => attrs.open, async (nval, oval) => {
  if (nval == true) {
    form.value = [];
    echoInfo()
  }
})
</script>

<style lang='scss' >
.u-person-detial-drawer {
  // z-index: 1200 !important
}
</style>